<script setup lang="ts">
import { FormInstance, FormRules } from "element-plus";
import { ref, reactive } from "vue";

import { userAPI } from "../../api/user";
// 加载状态
const loading = ref(false);
// 表单切换
const toggle = ref(true);
/**
 * 登录相关
 */
interface LoginRuleForm {
  username: string;
  password: string;
}
// 表单引用
const loginRuleFormRef = ref<FormInstance>();
// 表单数据
const loginRuleForm = reactive<LoginRuleForm>({
  username: "",
  password: "",
});
// 表单验证规则
const loginRules = reactive<FormRules<LoginRuleForm>>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      message: "账号不能为空",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { message: "密码不能为空", trigger: "blur" },
  ],
});

// 登录事件
const handleLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        const res = await userAPI.login(loginRuleForm);
        // 调用electronAPI通知主进程用户已登录
        if (
          (window as any).electronAPI &&
          (window as any).electronAPI.loginSuccess
        ) {
          await (window as any).electronAPI.store.set("user", res);
          // 连接建立后跳转到主页面
          (window as any).electronAPI.loginSuccess();
        } else {
          console.error("electronAPI不可用或loginSuccess方法未定义");
        }
      } catch (error) {
        console.error("登录失败:", error);
      } finally {
        loading.value = false;
      }
    } else {
      console.error("表单验证失败");
    }
  });
};
/**
 * 注册相关
 */
interface RegisterRuleForm {
  username: string;
  password: string;
  confirmPassword: string;
  email: string;
}
const registerRuleFormRef = ref<FormInstance>();
const registerRuleForm = reactive<RegisterRuleForm>({
  username: "",
  password: "",
  confirmPassword: "",
  email: "",
});
const registerRules = reactive<FormRules<RegisterRuleForm>>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 3,
      max: 8,
      message: "用户名长度必须在3到8个字符",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 10, message: "密码长度必须在6到10个字符", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (
        _rule: any,
        value: string,
        callback: (error?: string | Error) => void
      ) => {
        if (value !== registerRuleForm.password) {
          callback("两次输入密码不一致");
        } else {
          callback();
        }
      },
      message: "两次输入密码不一致",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      validator: (
        _rule: any,
        val: string,
        callback: (error?: string | Error) => void
      ) => {
        if (
          /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(
            val
          )
        ) {
          callback();
        } else {
          callback("请输入正确的邮箱格式");
        }
      },
      message: "请输入正确的邮箱格式",
      trigger: "blur",
    },
  ],
});
const handleRegister = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        await userAPI.register({
          username: registerRuleForm.username,
          password: registerRuleForm.password,
          email: registerRuleForm.email,
        });
        // 注册成功后切换到登录表单
        toggleForm();
      } catch (err) {
        console.error("注册失败", err);
      } finally {
        loading.value = false;
      }
    } else {
      console.error("表单验证失败");
    }
  });
};
// 切换表单
const toggleForm = () => {
  toggle.value = !toggle.value;
  // 切换表单时清空表单数据
  loginRuleFormRef.value?.resetFields();
  registerRuleFormRef.value?.resetFields();
  loading.value = false;
};

const find = () => {
  console.log("忘记密码");
};
</script>

<template>
  <!-- 登录页面容器 -->
  <div class="container soft-dynamic-bg">
    <h2>即时通讯</h2>
    <div class="container-form" v-if="toggle">
      <el-form
        ref="loginRuleFormRef"
        style="max-width: 600px"
        :model="loginRuleForm"
        :rules="loginRules"
        label-width="auto"
      >
        <el-form-item prop="username">
          <el-input v-model="loginRuleForm.username" placeholder="账 号" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            v-model="loginRuleForm.password"
            placeholder="密 码"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            style="width: 100%"
            type="primary"
            @click="handleLogin(loginRuleFormRef)"
            :loading="loading"
            >登录</el-button
          >
        </el-form-item>
        <el-form-item>
          <div class="footer">
            <el-link @click="toggleForm">注册账号</el-link>
            <span>|</span>
            <el-link @click="find">忘记密码</el-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="container-form" v-else>
      <el-form
        ref="registerRuleFormRef"
        style="max-width: 600px"
        :model="registerRuleForm"
        :rules="registerRules"
        label-width="auto"
      >
        <el-form-item prop="username">
          <el-input v-model="registerRuleForm.username" placeholder="账 号" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            v-model="registerRuleForm.password"
            placeholder="密 码"
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            type="password"
            v-model="registerRuleForm.confirmPassword"
            placeholder="确认密码"
          />
        </el-form-item>
        <el-form-item prop="email">
          <el-input v-model="registerRuleForm.email" placeholder="邮 箱" />
        </el-form-item>
        <el-form-item>
          <div
            style="
              display: flex;
              flex-direction: column;
              align-items: flex-start;
              margin-bottom: -10px;
              width: 100%;
            "
          >
            <el-button
              style="width: 100%"
              type="primary"
              @click="handleRegister(registerRuleFormRef)"
              :loading="loading"
              >注册</el-button
            >
            <span style="color: rgba(255, 0, 0, 0.6); font-size: 11px"
              >*请填入正确邮箱，以便后续使用</span
            >
          </div>
        </el-form-item>
        <el-form-item>
          <div class="footer">
            <el-link @click="toggleForm">< 已有帐号?去登录</el-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style lang="less" scoped>
/* 确保HTML和body占满整个窗口 */
:global(html),
:global(body) {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  overflow: hidden;
}

/* 登录容器占满整个窗口 */
.container {
  height: 100vh;
  width: 100vw;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  .footer {
    display: flex;
    justify-content: space-around;
    margin: 0 auto;
    font-size: 12px;
    margin-top: -16px;
    span {
      margin: 0 6px;
    }
  }
}

/* 按钮悬停效果 */
button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

/* 动态渐变背景 */
.soft-dynamic-bg {
  background: linear-gradient(
    135deg,
    #a2dcf7 0%,
    #89c2f0 25%,
    #ceb6f5 50%,
    #b89cf0 75%,
    #a2dcf7 100%
  );
  background-size: 300% 300%;
  animation: softGradient 12s ease infinite;
}

@keyframes softGradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}
</style>